const { Service } = require("egg");

class RoleAclService extends Service {
    /**
     * 查询某个角色权限关系
     * @param {*} rid
     * @param {*} aid
     */
    async findByQuery(rid, aid) {
        let res = await this.app.mysql.query(
            "select * from r_role_acl where rid = ? and aid = ? limit 0, 1",
            [rid, aid]
        );
        return res[0];
    }

    /**
     * 获取角色权限列表
     * @param {*} type
     */
    async readListByQuery(type) {
        let sql = `
            select
                r.id as rid,
                r.name as rname,
                a.id as aid,
                a.name as aname,
                a.path as apath,
                a.method as amethod
            from role as r
                join r_role_acl as rra on r.id = rra.rid
                join acl as a on rra.aid = a.id and a.type = ?
            order by r.sort;
        `;
        let params = [type];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }

    /**
     * 添加一个角色权限关系
     * @param {*} rid
     * @param {*} aid
     */
    async add({ rid, aid }) {
        // 如果已存在，就不能添加了
        let record = await this.findByQuery(rid, aid);
        if (record) {
            this.ctx.cast(403, "该角色已有这个权限");
        }
        // 添加
        let res = await this.app.mysql.query(
            "insert into r_role_acl (rid, aid) values (?, ?)",
            [rid, aid]
        );
        // 返回执行结果
        return res;
    }
}

module.exports = RoleAclService;
